<?php

namespace App\Library\Service;

use App\Library\Logic\ShopUserAddressLogic;
use App\Library\Requests\Base\BasePageRequest;
use App\Library\Requests\Base\SerialNumberRequest;
use App\Library\Requests\UserAddress\UserAddressAddRequest;
use App\Library\Requests\UserAddress\UserAddressEditRequest;
use Illuminate\Http\JsonResponse;

class UserAddressService extends BaseService
{
    public function __construct(ShopUserAddressLogic $logic)
    {
        $this->logic = $logic;
    }

    /**
     *
     * @param BasePageRequest $request
     * @return JsonResponse
     *
     */
    public function paging(BasePageRequest $request): JsonResponse
    {
        return success($this->logic->paging($request));
    }

    public function add(UserAddressAddRequest $request): JsonResponse
    {
        self::common($request);
        $this->logic->insertForModel(array_merge(['userId' => USERID], handleRequest($request)));
        return success();
    }

    public function edit(UserAddressEditRequest $request): JsonResponse
    {
        $model = $this->logic->findBySerialNumber($request);
        if (is_null($model)) return fail(433);
        self::common($request);
        $this->logic->updateForModel(array_merge(['userId' => USERID], handleRequest($request)), $model);
        return success();
    }

    public function delete(SerialNumberRequest $request): JsonResponse
    {
        $model = $this->logic->findBySerialNumber($request);
        if (is_null($model)) return fail(433);
        $model->delete();
        return success();
    }

    public function common($request): void
    {
        if ($request->uaDefault) {
            $defaultModel = $this->logic->findByWhere([
                'userId' => USERID,
                'uaDefault' => 1
            ]);

            if (!is_null($defaultModel)) {
                $defaultModel->ua_default = 0;
                $defaultModel->save();
            }
        }

        if ($request->uaIsRefund) {
            $refundModel = $this->logic->findByWhere([
                'userId' => USERID,
                'uaIsRefund' => 1,
                'type' => 1
            ]);
            if (!is_null($refundModel)) {
                $refundModel->ua_is_Refund = 0;
                $refundModel->save();
            }
        }
    }

    /**
     * default
     * @return JsonResponse
     *
     */
    public function default(): JsonResponse
    {
        return success(
            $this->logic->findByWhere([
                'userId' => USERID,
                'type' => 0,
                'uaDefault' => 1,
                'uaIsRefund' => 0
            ])
        );
    }
}
